package com.zy.batiya.controller;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zy.batiya.domain.InventoryItem;
import com.zy.batiya.domain.Pager;
import com.zy.batiya.dto.InventoryItemDTO;
import com.zy.batiya.service.InventoryItemService;

@Controller
public class InventoryController {
  
  private Logger logger = LoggerFactory.getLogger(InventoryController.class);
  
  @Autowired
  private InventoryItemService inventoryItemService;
  
  @ResponseBody
  @RequestMapping(value = "getInventoryItemPage")
  public String getStockPage(HttpServletRequest request) {
      Map<String, Object> rsMap = new HashMap<String, Object>();
      Map<String, String> map = new HashMap<String, String>();
      ObjectMapper mapper = new ObjectMapper();
      StringWriter writer = new StringWriter();
      String result = "";
      try {
          Integer draw = Integer.parseInt(request.getParameter("draw"));
          Integer start = Integer.parseInt(request.getParameter("start"));
          Integer length = Integer.parseInt(request.getParameter("length"));
          
          String roomNumber = request.getParameter("roomNumber");
          String partner_pid = request.getParameter("partner_pid");
          
          String orderColumn = request.getParameter("order[0][column]");
          String columnName = request.getParameter("columns[" + orderColumn + "][data]");
          String orderDir = request.getParameter("order[0][dir]");
          
          Pager<InventoryItemDTO> pager = new Pager<>();
          InventoryItemDTO dto = new InventoryItemDTO();
          dto.setRoomNumber(roomNumber);
          dto.setPartner_pid(partner_pid);
          pager.setT(dto);
          pager.setPagenow(start / length + 1);
          pager.setSize(length);
          pager.setOrderCol(columnName);
          pager.setOrder(orderDir);
          
          Pager<List<InventoryItem>> stations = inventoryItemService.list(pager);
          
          rsMap.put("data", stations.getT());
          rsMap.put("recordsTotal", stations.getTotal());
          rsMap.put("recordsFiltered", stations.getTotal());
          rsMap.put("draw", draw);
          mapper.writeValue(writer, rsMap);
          result = writer.toString();
      } catch (Exception e) {
          e.printStackTrace();
      }
      return result;
  }
}
